export default {
    namespaced: true,
    state:{
         cartData: [] 
    },
    mutations:{
        SET_CART(state,payload){
            let target = state.cartData.find(item => item.id === payload.id)
            if (!target) {
                let obj ={
                    title: payload.title,
                    price: payload.price,
                    count: 1,
                    id: payload.id
                }
            state.cartData.push(obj)
        }else{
            target.count++
        }
    },
    DECREASE_CART(state,payload){
        let target = state.cartData.find(item => item.id === payload.id)
        if (target) {
            target.count--
            }
        if(target.count < 1){
            state.cartData = state.cartData.filter(item => item.id !== payload.id)
        }
    }
    
},
    actions:{
        ADD_CART(context,payload){
            context.commit ('SET_CART',payload)
            context.commit ('product/DECREASE_INVENTORY',payload.id,{ root: true })
        },
        REMOVE_CART(context,payload){
            context.commit ('DECREASE_CART',payload)
            context.commit('product/INCREASE_INVENTORY',payload,{root:true})
        }
    },
    getters:{
        total(state) {
            return (state.cartData.reduce((total,item)=>{
                return total += item.price * item.count}, 0)).toFixed(2)
            }
          
    },
}
